package com.nosnow.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.nosnow.oss.service.OssService;
import com.nosnow.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author by bingHeng
 * @version 1.0
 * @Create 2020/4/3 23:55
 */

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFileAvater(MultipartFile file) throws Exception{

        // 1. 获取服务器域节点
        String endpoint = ConstantPropertiesUtils.END_POINT;

        // 2. 获取accessKeyId
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;

        // 3. 获取access秘钥
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;

        // 4. 获取bucketName，OSS中的 bucketName
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        // 5. 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 6. 获取上传文件的输入流
        InputStream inputStream = file.getInputStream();

        // 7. 获取文件名称, 为了保证文件名称在OSS中不重复（重复会被覆盖），添加uuid随机码
        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        filename = uuid + filename;

        // 8. 在OSS中将文件按照日期进行分类
        String datePath = new DateTime().toString("yyyy/MM/dd");
        filename = datePath + "/" + filename;

        // 9. 调用OSS方法实现上传: bucketName, 文件名称（可以包含文件路径，例如：aa/bb/cc/file.getOriginalFilename(), inputStream文件流）
        ossClient.putObject(bucketName, filename, inputStream);

        // 10. 关流
        ossClient.shutdown();

        // 11. 手动拼接上传到oss的路径，并返回
        String url = ConstantPropertiesUtils.URL + filename;
        return url;
    }
}
